import FlowEcharts from "./lib/FlowEcharts";
import {
  data,
  flags
} from './lib/ebar-data.js';

export default class Ebar {
  constructor(basicCesium) {
    this.basicCesium = basicCesium
    this.viewer = basicCesium.viewer;
    this._instance = null;
    this.option = null;
    this.currentYear = 1890;
    this.listen = null;
    this._initChart();
    this._initTime();
  }

  _initTime() {
    this.start = Cesium.JulianDate.fromDate(new Date('1950-01-01'));
    this.stop = Cesium.JulianDate.fromDate(new Date('2015-12-31'));
    this.viewer.clock.startTime = this.start.clone();
    this.viewer.clock.stopTime = this.stop.clone();
    this.viewer.clock.currentTime = this.start.clone();
    this.viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
    this.viewer.clock.multiplier = 24 * 60 * 60 * 30 * 12;
    this.viewer.timeline.zoomTo(this.start, this.stop);
    this.listen = this.viewer.clock.onTick.addEventListener((e) => {
      let parseDate = Cesium.JulianDate.toDate(e.currentTime);
      let year = parseDate.getFullYear();
      if (this.currentYear != year) { 
        this.currentYear = year;
        this.updateYear(year);
      }
    })
  }

  _initChart() {
    const updateFrequency = 2000;
    const dimension = 0;
    const countryColors = {
      Australia: '#00008b',
      Canada: '#f00',
      China: '#ffde00',
      Cuba: '#002a8f',
      Finland: '#003580',
      France: '#ed2939',
      Germany: '#000',
      Iceland: '#003897',
      India: '#f93',
      Japan: '#bc002d',
      'North Korea': '#024fa2',
      'South Korea': '#000',
      'New Zealand': '#00247d',
      Norway: '#ef2b2d',
      Poland: '#dc143c',
      Russia: '#d52b1e',
      Turkey: '#e30a17',
      'United Kingdom': '#00247d',
      'United States': '#b22234'
    };
    const years = [];
    for (let i = 0; i < data.length; ++i) {
      if (years.length === 0 || years[years.length - 1] !== data[i][4]) {
        years.push(data[i][4]);
      }
    }

    function getFlag(countryName) {
      if (!countryName) {
        return '';
      }
      return (
        flags.find(function (item) {
          return item.name === countryName;
        }) || {}
      ).emoji;
    }
    let startIndex = 10;
    let startYear = years[startIndex];

    this.option = {
      animation: !0,
      backgroundColor: 'rgba(17, 19, 42, 0.2)',
      title: [{
        text: 'Cesium + Echarts 动态排序柱状图',
        subtext: 'cesium echarts dong tai pai xu zhu zhuang tu',
        left: 'center',
        top: 10,
        textStyle: {
          color: '#fff'
        },
        subtextStyle: {
          color: '#fff'
        }
      }, {
        id: 'statistic',
        text: '人均收入',
        left: 180,
        top: 40,
        width: 100,
        textStyle: {
          color: '#fff',
          fontSize: 16
        }
      }],
      tooltip: {
        show: true,
        trigger: 'item'
      },
      grid: {
        left: 140,
        top: 80,
        bottom: 100,
        width: '25%'
      },
      xAxis: {
        max: 'dataMax',
        axisLabel: {
          formatter: function (n) {
            return Math.round(n) + '';
          },
          color: '#fff'
        },
        splitLine: {
          show: !1
        },
        axisLine: {
          show: !1
        },
        axisTick: {
          show: !1
        },
      },
      dataset: {
        source: data.slice(1).filter(function (d) {
          return d[4] === startYear;
        })
      },
      yAxis: {
        type: 'category',
        inverse: true,
        max: 10,
        axisLabel: {
          show: true,
          fontSize: 12,
          formatter: function (value) {
            return value + '{flag|' + getFlag(value) + '}';
          },
          color: '#fff',
          lineHeight: 22,
          rich: {
            flag: {
              fontSize: 20,
              padding: [1, 5, 5, 5],
              verticalAlign: 'middle'
            }
          }
        },
        splitLine: {
          show: !1
        },
        axisLine: {
          show: !1
        },
        axisTick: {
          show: !1
        },
        animationDuration: 300,
        animationDurationUpdate: 300
      },
      series: [{
        realtimeSort: true,
        seriesLayoutBy: 'column',
        type: 'bar',
        itemStyle: {
          color: function (param) {
            return countryColors[param.value[3]] || '#5470c6';
          }
        },
        encode: {
          x: dimension,
          y: 3
        },
        label: {
          show: true,
          precision: 1,
          position: 'right',
          valueAnimation: true,
          fontFamily: 'monospace'
        }
      }],
      animationDuration: 0,
      animationDurationUpdate: updateFrequency,
      animationEasing: 'linear',
      animationEasingUpdate: 'linear',
      graphic: {
        elements: [{
          type: 'text',
          right: 160,
          bottom: 60,
          style: {
            text: startYear,
            font: 'bolder 80px monospace',
            fill: 'rgba(200, 200, 200, 0.45)'
          },
          z: 100
        }]
      }
    }
    this._instance == null ? this._instance = new FlowEcharts(this.viewer, this.option) : this._instance.updateOverlay();
  }

  updateYear(year) {
    if (this._instance == null) return;
    let source = data.slice(1).filter(function (d) {
      return d[4] === year;
    });
    if (source.length == 0) return;
    this.option.series[0].data = source;
    this.option.graphic.elements[0].style.text = year;
    this._instance.updateOverlay(this.option);
    console.log(year)
  }

  dispose() {
    this._instance = null;
    this.viewer.clock.onTick.removeEventListener(this.listen);
  }
}